import React from 'react';
import { Button, Icon, ActionSheet, Avatar, Tools } from 'weaver-mobile';
import './index.less';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { permissionType, getPermissionDatas, personOpt, groupOpt,userType } from './type';
import If, { Then, Else } from '../../../common/if';
import classNames from 'classnames';
import SelectDown from '../../../common/select-down';
import ShareView from '../../../common/share/components';
import Loading from '../../../common/loading';
import BackBtn from '../backbtn';

const getLabel = Tools.getLabel; 
const { SPECIFIED_USER, ANY_USER, OA_USER } = permissionType;
const { USER, CHATGROUP, DEPARTMENT, SUBCOMPANY } = userType;
const permissionDatas = getPermissionDatas();
const SHOWTAG = {
  DEPARTMENT: getLabel(523257, '部门'),
  SUBCOMPANY: getLabel(523258, '分部'),
  CHATGROUP: getLabel(523259, '群组') 
};

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;

if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

export class PersonItem extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      status: false
    }
  }

  showPersonSheet = () => {
    const buttons = [];
    let options = [];
    const { onPersonOptChange, person } = this.props;
    const { type } = person;

    this.setState({ status: !this.state.status});
    // 群组和人员有不一样的操作
    if (type === USER || type === SUBCOMPANY || type === DEPARTMENT) {
      options = personOpt();
    } else if (type === CHATGROUP) {
      options = groupOpt();
    }

    options.forEach(data => {
      buttons.push({
        content: <div className='person-picker-down'>
          <span className={classNames('text', {'del': data.value === 'delete'})}>{data.text}</span>
        </div>,
        onClick: () => onPersonOptChange(data.value, person, type)
      });
    });

    buttons.push({
      content: <div>{getLabel(523250, '取消')}</div>
    })

    ActionSheet.showActionSheetWithOptions({
      options: buttons,
      cancelButtonIndex: buttons.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
    (buttonIndex) => {
      this.setState({ status: !this.state.status });
    });
  }

  render () {
    const { personValue, person, groupId, changeGroupId } = this.props;
    const { status } = this.state;
    const personValText = personOpt().find(p => p.value === personValue).text;
    const { type } = person;

    return (
      <li>
        {type !== USER ? <Avatar name={person.name} isGroup={true} type='1'/> : <Avatar userId={person.id} />}
        <div className='person-info'>
          <span className='person-name'>{person.lastname || person.name}</span>
          <If condition={type !== USER}>
            <Then>
              <span 
                className={classNames('group-size', {'group-size-down': groupId === person.id})}
                onClick={() => changeGroupId(person.id)}
              >
                <span className={`person-tag person-tag-${type}`}>{SHOWTAG[type]}</span>
                {person.memberSize}人&nbsp;&nbsp;
                {person.exceptMember ? `${getLabel(523260, '不参与填写人员')}：${person.exceptMember}` : ''}
              </span>
            </Then>
            <Else>
               <span className='person-department'>{person.departmentName}</span>
            </Else>
          </If>
        </div>
        <span className='person-picker' onClick={this.showPersonSheet}>
          {personValText}
          <If condition={status}>
            <Then>
              <Icon type={'up'}></Icon>
            </Then>
            <Else>
              <Icon type={'down'}></Icon>
            </Else>
          </If>
        </span>
      </li>
    )
  }
}

@inject('formPermissionStore')
@withRouter
@observer
export default class Permission extends React.Component {
  constructor(props) {
    super(props);
    this.store = props.formPermissionStore;
    this.showInTab = Boolean(props.showInTab); // 用来判断是否在power组件中展示

    const appid = props.appid || props.match.params.id;
  
    this.store.init(appid, this.showInTab);
    this.state = {
      browserHrmValue: [],
      personValue: 'write',
      groupId: '', // 用来控制群组未选择人员的样式
    };
  }

  onPickerOk = (value) => {
    const { changePermissionType } = this.store;

    changePermissionType(value);
  }

  changeGroupId = groupId => {
    if (groupId !== this.state.groupId) {
      this.setState({ groupId });
    } else {
      this.setState({ groupId : '' });
    }
  }

  onPersonOptChange = (value, person, type) => {
    const { changeBrowser } = this.store;
    const { pkId, id } = person;

    if(value === 'delete') {
      changeBrowser(id, type);
      return;
    } else if (value === 'groupNoWrite') {
      this.props.history.push({ pathname: `/form/permission/setgroupnowrite`, query: { pkId, conversationId: id}} );
    }
  }

  formatDatas = (permissionDatas) => {
    const datas = [];

    permissionDatas.forEach(data => {
      datas.push({
        id: data.value,
        name: data.label,
        label: data.text
      });
    });

    return datas;
  }

  render () {
    const { personValue, groupId } = this.state;
    const { browsers, browsersSize, permissionValue = ANY_USER, layout, setBrowsers, appMsg, appid, hasInit } = this.store;
    const { history } = this.props;
    const text = permissionDatas.find(p => p.value === permissionValue).text;
    const backBtnAble = window.backBtnAble;

    return (
      <div className='form-power'>
        <If condition={!hasInit}>
          <Then>
            <Loading loading={true} className='form-power-loading'/>
          </Then>
          <Else>
            <If condition={backBtnAble && !this.showInTab}>
              <BackBtn />
            </If>
            <div className={classNames('main' ,{ 'main-has-back': backBtnAble })}>
              <div className='picker'>
                <SelectDown 
                  datas={this.formatDatas(permissionDatas)}
                  selectedId={permissionValue}
                  onClick={this.onPickerOk}
                  clsName='power-picker'
                  downClsName='power-picker-down'
                  liHeight={65}
                  showCancel={true}
                />
                <div className='power-type-text'>{text}</div>
              </div>
              <If condition={permissionValue === ANY_USER || permissionValue === OA_USER}>
                <Button className='forward' onClick={() => history.push({ pathname: '/form/share', appName: appMsg.name, appid: appid })}>{getLabel(523370, '分享表单')}</Button>
              </If>
              {
                permissionValue === SPECIFIED_USER && 
                <div className='person-content'>
                  <div className='wrapper'>
                      <div className='add-person-btn' onClick={() => history.push(layout.path)}>
                      <Button type="primary">{getLabel(523262, '邀请他人填写')}</Button>
                      </div>
                      {
                        <Route
                          key='shareview'
                          path={layout.path}
                          render={() => (
                            <ShareView 
                              onSubmit={setBrowsers}
                              memberList={browsers} 
                            />
                          )}
                        />
                      }
                    <div>{getLabel(523263, '已添加')} {browsersSize || 0} {getLabel(523264, '人填写')}</div>
                    <div className='form-author'>{getLabel(523265, '表单所有者')}: {appMsg.creator}</div>
                  </div>
                  {
                    browsers.length > 0 && 
                    <ul className='person-list'>
                      {
                        browsers.map(person => (
                          <PersonItem 
                            key={`${person.lastname}_${USER}_${person.id}`}
                            type={USER} 
                            onPersonOptChange={this.onPersonOptChange} 
                            person={person} 
                            personValue={personValue}
                            groupId={groupId}
                            changeGroupId={this.changeGroupId}
                          />
                        ))
                      }
                    </ul>
                  }
                </div>
              }
            </div>
          </Else>
        </If>
      </div>
    );
  }
}
